import java.util.LinkedList;

class Solution {
    public List<List<String>> partition(String s) {
        List<List<String>> res = new LinkedList<>();
        dfs(s, 0, 1, new LinkedList<String>(), res);
        f(s, 0, new LinkedList<String>(), res);
        return res;
    }

    public void dfs(String s, int start, int end, LinkedList<String> path, List<List<String>> res){
        if (end > s.length())
            return;
        
        if (check(s, start, end)){
            path.add(s.substring(start, end));
            if (end == s.length())
                res.add(new ArrayList<String>(path));
            dfs(s, end, end+1, path, res);
            path.removeLast();
        }
        dfs(s, start, end+1, path, res);
    }

    public boolean check(String s, int start, int end){
        while(start < end-1){
            if (s.charAt(start) != s.charAt(end-1))
                return false;
            start++;
            end--;
        }
        return true;
    }

    public void f(String s, int i, LinkedList<String> path, List<List<String>> res){
        if (i==s.length()){
            res.add(new ArrayList<String>(path));
            return;}

        for (int j = i; j < s.length(); j++){
            if(check(s, i, j+1)){
                path.add(s.substring(i, j+1));
                f(s, j+1, path, res);
                path.removeLast();
            }
        }
    }
}
